package com.yjn.blog.controller;

import com.alibaba.fastjson.JSON;
import com.yjn.blog.entity.CommonWebUser;
import com.yjn.blog.model.UserModel;
import com.yjn.blog.model.http.UserReq;
import com.yjn.blog.model.http.UserResp;
import com.yjn.blog.service.UserService;
import com.yjn.blog.util.ErrorMessage;
import com.yjn.blog.util.RedisUtil;
import com.yjn.blog.util.bean.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.UUID;

/**
 * Classname: UserController
 * Package: com.yjn.blog.controller
 * Description:
 *
 * @Author 余集楠
 * @Create 2024/7/16 0016 19:52
 * @Version 1.8
 */
@RestController
@RequestMapping(value="/api")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RedisUtil redisUtil;

    @PostMapping(value="/auth/regist")
    public BaseResponse<Boolean>regist(@Valid @RequestBody String username,String password){
        return BaseResponse.ok(userService.regist(username,password));
    }

    @PostMapping(value="/auth/login")
    public BaseResponse login(@Valid @RequestBody UserReq req) throws Exception {

        Object existObj=redisUtil.get(req.getUsername());
        //判断username是不是空或者是不是和数据库的一致
        if(existObj==null||!existObj.toString().equals(req.getUsername())){
            return BaseResponse.error(ErrorMessage.USER_ERROR);
        }else{
            redisUtil.del(req.getUsername());

            UserModel userModel= userService.login(req);
            CommonWebUser commonWebUser=new CommonWebUser();
            BeanUtils.copyProperties(commonWebUser,userModel);
            String token = UUID.randomUUID().toString().replaceAll("-","");
            //设置token超时时间为一个月，实际根据需求确定
            redisUtil.set(token, JSON.toJSONString(commonWebUser),60*60*24*30);
            UserResp resp=new UserResp();
            resp.setToken(token);
            return BaseResponse.ok(resp);
        }
    }

    @RequestMapping(value="/auth/me")
    public BaseResponse<UserModel>userInfo(@Valid @RequestBody String username){
        return BaseResponse.ok(userService.userInfo(username));
    }

}
